package com.colabo.j2ee.web.oaf.security.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.pkgenerator.IPKGenerator;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.core.vo.RecordObject;
import com.colabo.j2ee.web.oaf.security.IResourceRelationService;
import com.colabo.j2ee.web.oaf.security.model.IPResourceRelationVO;
import com.colabo.j2ee.web.oaf.vo.IPResMenuVO;

public class ResourceRelationServiceImpl extends DefaultServiceImpl implements IResourceRelationService {
	Log log = LogFactory.getLog(ResourceRelationServiceImpl.class);

	public void saveRelation(RecordObject coreResource, RecordObject relatedResource) throws ServiceException {
		if (coreResource == null || relatedResource == null) {
			return;
		}

		IPKGenerator keyGen = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		IPResourceRelationVO vo = new IPResourceRelationVO();
		vo.setResrelaky(keyGen.getUUIDKey(vo));
		vo.setCoreResourceCode(((IPResMenuVO)coreResource).getMenuky());
		vo.setCoreResourceType(coreResource.getClass().getName());
		vo.setRelatedResourceCode(relatedResource.getLogicalKey());
		vo.setRelatedResourceType(relatedResource.getClass().getName());
		save_Hibernate_Object(vo);
	}

	public List getAllRelatedResources(RecordObject resource) throws ServiceException {
		if (resource == null) {
			return new ArrayList(0);
		}
		Map m = new HashMap();
		m.put("coreResourceType", resource.getClass().getName());
		m.put("coreResourceCode", resource.getLogicalKey());
		List l = find_iBatis("web.getAllRelatedResources", m), 
		ret = new ArrayList();
		String className, id;
		for (Iterator it = l.iterator(); it.hasNext();) {
			IPResourceRelationVO resvo = (IPResourceRelationVO) it.next();
			className = resvo.getRelatedResourceCode();
			id = resvo.getRelatedResourceType();
			try {
				ret.add(findByID_Hibernate_Get(Class.forName(className), id));
			} catch (ClassNotFoundException e) {
				log.warn(e);
			}
		}
		return ret;
	}
}
